﻿using Abp.Auditing;
using Abp.Dependency;
using Abp.Web.Models;
using GN.Pay.Application.Dto.Output;
using GN.Pay.Application.GatewayApp;
using GN.Pay.Application.GatewayApp.Dto.Input;
using GN.Pay.Application.GatewayApp.Dto.Output;
using GN.Pay.Core.Services;
using GN.Pay.GatewayWeb.Controllers.PayRoute;
using GN.Pay.GatewayWeb.Models;
using GN.Pay.TradeChannel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GN.Pay.GatewayWeb.Controllers
{
    /// <summary>
    /// Wap
    /// </summary>
    public class WapController : PayControllerBase
    {
        private readonly ITradeApplyAppService service;
        private readonly IIocManager iocManager;
        protected readonly IClientInfoProvider clientInfo;


        public WapController(ITradeApplyAppService service, IClientInfoProvider clientInfo,
            IIocManager iocManager)
        {
            this.service = service;
            this.iocManager = iocManager;
            this.clientInfo = clientInfo;

        }

        /// <summary>
        /// 判断是否是微信浏览器
        /// </summary>
        public bool IsWeixin
        {
            get
            {
                string userAgent = Request.UserAgent; ;
                if (userAgent.ToLower().Contains("micromessenger"))
                {
                    if (!userAgent.ToLower().Contains("wxwork"))
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        /// <summary>
        /// 支付申请
        /// </summary>
        /// <param name="id">申请号</param>
        /// <returns></returns>
        public ActionResult Pay(string id, string returnUrl = "")
        {
            var output = new ServiceMessageResultOutput<CashiePayApplyOutput>
            {
                Result = null,
                Success = false
            };
            if (string.IsNullOrWhiteSpace(id))
            {
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                output.Error = new ServiceErrorMessageOutput
                {
                    Code = 0,
                    Message = "付款申请出错.未指定付款申请号"
                };
                output.Result = null;
                output.Success = false;
                return View(output);
            };
            ViewBag.IsWeixin = IsWeixin;
            try
            {
                var outDto = service.CashiePayApply(new CashiePayApplyInput() { ApplyId = id, ChannelType = ChannelType.WebApp });
                if (outDto == null)
                {
                    output.Error = new ServiceErrorMessageOutput
                    {
                        Code = 0,
                        Message = string.Format("支付申请号:{0}可能无效、已支付过或支付期限过期", id)
                    };
                    return View(output);
                }
                output.Error = null;
                output.Result = outDto;
                output.Success = true;
                return View(output);
            }
            catch (Exception err)
            {
                output.Error = new ServiceErrorMessageOutput
                {
                    Code = 0,
                    Message = string.Format("支付出错:｛0｝", err.Message)
                };
                return View(output);
            }
        }

        /// <summary>
        /// 银行卡列表
        /// </summary>
        /// <param name="id">申请</param>
        /// <returns></returns>
        public ActionResult BankList(string id)
        {
            var output = new ServiceMessageResultOutput<List<BankCardOutput>>
            {
                Result = null,
                Success = false
            };
            if (string.IsNullOrWhiteSpace(id))
            {
                output.Error = new ServiceErrorMessageOutput
                {
                    Code = 0,
                    Message = "付款申请出错.未指定付款申请号"
                };
                return View(output);
            }
            ViewBag.ApplyId = id;
            try
            {
                var bankService = iocManager.Resolve<IBankCardAppService>();
                var bankCardList = bankService.MerchantMemberBankCardList(id);
                output.Error = null;
                output.Result = bankCardList;
                output.Success = true;
                return this.View(output);
            }
            catch (Exception err)
            {
                output.Error = new ServiceErrorMessageOutput
                {
                    Code = 0,
                    Message = string.Format("支付出错:｛0｝", err.Message)
                };
                return View(output);
            }
        }

        /// <summary>
        /// 付款通道
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult PayChannel(PayChannelModel input)
        {
            if (input == null)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "付款出错,申请信息为null")));
            }
            if (string.IsNullOrWhiteSpace(input.ApplyId))
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "付款出错,申请号为空")));
            }
            if (string.IsNullOrWhiteSpace(input.ChannelId))
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "付款出错,支付通道为空")));
            }
            if (!PayRouteInstaller.Instance.IsRegisterRoute(input.ChannelId))
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, string.Format("不支持支付通道:{0} ", input.ChannelId))));
            }
            try
            {
                var route = PayRouteInstaller.Instance.Resolve(iocManager, input.ChannelId);
                if (!route.IsSupportWap)
                {
                    return this.Json(new AjaxResponse(new ErrorInfo(0, "付款出错,不支持 Wap 支付")));
                }
                var payInput = new PayChannelInput()
                {
                    AppId = "Cashie",
                    ApplyId = input.ApplyId,
                    BankCradPayId = input.BankCradPayId,
                    MerchantId = "Cashie",
                    ChannelId = input.ChannelId,
                    ClientIP = clientInfo.ClientIpAddress == null ? "" : clientInfo.ClientIpAddress,
                };
                var result = service.PayChannelRegister(payInput);
                return this.Json(new AjaxResponse(result));
            }
            catch (Exception err)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, string.Format("付款出错,{0}", err.Message))));
            }
        }

        /// <summary>
        /// 支付跳转
        /// </summary>
        /// <param name="tradeNo">交易号</param>
        /// <returns></returns>
        public ActionResult PayRedirectResult(string tradeNo)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tradeNo))
                {
                    return this.WapErrorView("交易提示", "交易号为空");
                }
                var service = iocManager.Resolve<ITradeCacheService>();
                var notify = service.GetPayReturnNotify(tradeNo);
                if (notify == null)
                {
                    return this.WapErrorView();
                }
                if (string.IsNullOrWhiteSpace(notify.ReturnUrl))
                {
                    return this.WapErrorView();
                }
                var notifyService = iocManager.Resolve<ITradeNotifyService>();
                var dic = notifyService.Sign(notify);
                string url;
                if (notify.ReturnUrl.Contains("?"))
                {
                    url = notify.ReturnUrl + "&" + dic.UrlLinkString();
                }
                else
                {
                    url = notify.ReturnUrl + "?" + dic.UrlLinkString();
                }
                return new RedirectResult(url);
            }
            catch (Exception err)
            {
                this.Logger.Error(err.Message, err);
                return this.WapErrorView();
            }
        }
    }
}